package com.mos.action;

import com.mos.base.Globl;
import com.mos.base.action.BaseAction;
import com.mos.entity.Accessory;
import com.mos.service.AccessoryService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Package Name: com.mos.action
 * User: grq
 * Date: 2016/4/6
 * Time: 9:55
 * Description:some des here!
 */
@Controller
@RequestMapping("/accessory")
public class AccessoryAction extends BaseAction {


    private final Logger logger = Logger.getLogger(AccessoryAction.class);

    @Autowired
    private AccessoryService accessoryService;


    @ResponseBody
    @RequestMapping("/detail/{id}")
    public Accessory path(@PathVariable("id") String id) {
        return accessoryService.getById(id);
    }


    /*************************
     * 1、大字段访问
     ****************************************/
    //存储于附件中的大字段访问
    @ResponseBody
    @RequestMapping("/html/{id}")
    public String html(@PathVariable("id") String id) {
        return accessoryService.getHtml(id);
    }


    /*************************
     * 2、uploadify 上传及访问
     ****************************************/

    //uploadify 上传
    @ResponseBody
    @RequestMapping("/uupload")
    public String uupload(@RequestParam(value = "file", required = false) MultipartFile[] file) throws Exception {
        //由于使用uploadify的ajax提交，响应类型须是text/plain，因此方法只能返回string（此时spring mvc 会使用响应类型为text/plain 的StringHttpConverter进行数据转换）！
        //否则， 若返回其他 对象 ，spring mvc 会使用jsonHttpconverter， 它的响应类型是application/json ，此时uploadify会提示http 406 错误！

        String[] tmpFileName = accessoryService.uploadify(file);

        return "";
    }

    /**
     * 上传文件
     * @param name
     * @param filePath
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/upload")
    public Map<String,String> upload(@RequestParam("name") String name,@RequestParam("filePath") String filePath) throws Exception {
        Map<String,String> tmpFile = accessoryService.upload(name,filePath);
        return tmpFile;
    }

    //uploadify所上传图片附件访问-->根据附件id加载图片
    @RequestMapping("/uimage/{id}")
    public ModelAndView uimage1(@PathVariable("id") String id) throws IOException {
        String path = accessoryService.getPath(id);

        File file = null;
        byte[] data = null;
        if (StringUtils.isNotBlank(path)) {
            path = Globl.FILE_ROOT_DIR + path;
            file = new File(path);
        }
        if (null != file) {
            data = FileCopyUtils.copyToByteArray(new FileInputStream(file));
        }
        return super.createStreamViewOnly(data);
    }

    //uploadify所上传图片附件访问-->根据绝对地址加载图片(用于后台预览图片)
    @RequestMapping("/uimage/absolut")
    public ModelAndView uimage2(@RequestParam("p") String path) throws IOException {

        File file = null;
        byte[] data = null;
        if (StringUtils.isNotBlank(path)) {
            path = Globl.FILE_ROOT_DIR + path;
            file = new File(path);
        }
        if (null != file) {
            data = FileCopyUtils.copyToByteArray(new FileInputStream(file));
        }
        return super.createStreamViewOnly(data);
    }


    /*************************
     * 3、ckeditor上传及访问*
     ****************************************/

    //ckeditor 上传
    @RequestMapping("/cupload")
    public void cupload(
            @RequestParam(value = "upload", required = false) MultipartFile file,
            @RequestParam(value = "CKEditorFuncNum", required = false) String funcNum,
            HttpServletResponse response
    ) throws IOException {


        /**
         * 保存文件
         */
        String partfilename = accessoryService.ckeditor(file);


        String path = "";
        String imgUrl = "\"" + path + "accessory/cimage/absolut?p=" + partfilename + "\"";

        /**
         * 本来在客户端处理，但是蛋疼的ie递归触发iframe的onload事件不得已改为server端处理：
         */
        StringBuffer sb = new StringBuffer();
        sb.append("<script type=\"text/javascript\">");
        sb.append("window.parent.CKEDITOR.tools.callFunction(");
        sb.append(funcNum);
        sb.append(",");
        sb.append(imgUrl);//文件名
        sb.append(",");
        sb.append("\"\"");
        sb.append(");");
        sb.append("</script>");

        PrintWriter writer = response.getWriter();
        writer.append(sb.toString());

    }

    //ckeditor所上传图片附件访问-->根据绝对地址加载图片
    @RequestMapping("/cimage/absolut")
    public ModelAndView cimage1(@RequestParam("p") String path) throws IOException {

        File file = null;
        byte[] data = null;
        if (StringUtils.isNotBlank(path)) {
            //由于将f:/lyl/cke/201412/123245463434.jpg-->cke/201412/123245463434.jpg故此处需将其还原
            file = new File(Globl.FILE_ROOT_DIR + path);
        }
        if (null != file) {
            data = FileCopyUtils.copyToByteArray(new FileInputStream(file));
        }
        return super.createStreamViewOnly(data);
    }


}
